package com.baizhi.service.impl;

import com.baizhi.dao.FoodDao;
import com.baizhi.entity.Food;
import com.baizhi.service.FoodService;
import com.baizhi.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class FoodServiceImpl implements FoodService {

    @Override
    public List<Food> showFoods(Integer pageNum, Integer pageSize) {
        SqlSession sqlSession = null;
        List<Food> foods = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            FoodDao dao = sqlSession.getMapper(FoodDao.class);
            foods = dao.selectFoods(pageNum, pageSize);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        return foods;
    }

    @Override
    public Food showFoodById(Integer id) {
        SqlSession sqlSession = null;
        Food food = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            FoodDao dao = sqlSession.getMapper(FoodDao.class);
            food = dao.selectFoodById(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        return food;
    }

    @Override
    public void addFood(Food f) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            FoodDao dao = sqlSession.getMapper(FoodDao.class);
            dao.insertFood(f);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void removeFoodById(Integer id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            FoodDao dao = sqlSession.getMapper(FoodDao.class);
            dao.deleteFoodById(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateFood(Food f) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            FoodDao dao = sqlSession.getMapper(FoodDao.class);
            dao.updateFood(f);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
    }
}
